﻿var accountManager = function () {

    var action = path + '/action/powerdb/designer/';

    // 信息jqGrid表格id
    var accountGridTableSelector = '#grid-table';
    var dbInfoTableSelector = '#dbInfo-table';
    var addProjectJqgridTableSelector = '#addProjectJqgridTable';
    var addDbJqgridTableSelector = '#addDbJqgridTable';
    var projectGridTableSelector = '#project-table';
    var addedAccRelProjTableSelector = '#addedAccRelProjTable';
    var addedAccRelDbTableSelector = '#addedAccRelDbTable';

    // 信息新增/修改弹窗formId
    var accountAddOrEditModelForm = '#accountAddOrEditModelForm';
    var searchAccountForm = '#searchAccountForm';
    var searchProjectForm = '#searchProjectForm';
    var searchDbConnInfoForm = '#searchDbConnInfoForm';

    var getDbUrl = action + 'accountManage/getDbRelAccount';
    var getProUrl = action + 'accountManage/getAccountProject';
    var findAllProjectUrl = action + 'project/';
    var findAllDbUrl = action + 'dbConnInfo/';
    var delDbUrl = action + 'accountManage/deleteAccountRelDbConnInfo';

    /** 枚举关键字*/
    var enums = ['sec_account-sex', 'sec_account-delStatus', 'sec_account-active', 'sec_account-status'];
    var enums1 = ['pdm_account_rel_project-projectAuto'];
    /** 获取所有需要翻译的枚举 */
    var enumMap = sPost.getEnumMap(enums);
    var enumMap1 = sPost.getEnumMap(enums1);

    var id = '';

    var accountGridSetting = {
        gridId: accountGridTableSelector,
        pagerId: '#grid-pager',
        datatype: 'local',
        data: [],
        //height: 125,
        gridHeightType: 2,
        url: null,
        onSelectRow: function (id) {
            // 根据id获取选中行数据
            //var resData = $(accountGridTableSelector).jqGrid('getRowData', id);
            //id = resData.id;
            //slog.log(id);
            accountManager.searchAccountRelations(true);
            accountManager.searchAccountRelations(false);
        },
        multiselect: false,
        rownumbers: true,
        altRows: true,
        autowidth: true,
        rowNum: 5,
        rowList: [5, 15, 30, 100],
        colNames: ['id', '中文名', '英文名', '年龄', '性别', '电话', '账户名', '手机', '账户状态', '账户有效性'
            , '账户有效开始时间', '账户有效结束时间', '上次登录时间,','修改人名称', '修改人编号', '分组编号', '删除状态'
            , '生日', '修改时间', '创建时间'],
        colModel: [
            {name: 'id', index: 'id', width: 0, align: 'center', hidden: true},
            {name: 'nameCn', index: 'aNameCn', width: 0, align: 'center'},
            {name: 'nameEn', index: 'nameEn', width: 0, align: 'center'},
            {name: 'age', index: 'age', width: 0, align: 'center'},
            {name: 'sex', index: 'sex', width: 0, align: 'center'},
            {name: 'phone', index: 'phone', width: 0, align: 'center'},
            {name: 'username', index: 'username', width: 0, align: 'center', hidden: true},
            {name: 'cellPhone', index: 'cellPhone', width: 0, align: 'center'},
            {name: 'status', index: 'status', width: 0, align: 'center'},
            {name: 'active', index: 'active', width: 0, align: 'center', hidden: true},
            {name: 'activeStartTime', index: 'activeStartTime', width: 0, align: 'center', hidden: true},
            {name: 'activeEndTime', index: 'activeEndTime', width: 0, align: 'center', hidden: true},
            {name: 'lastLoginTime', index: 'lastLoginTime', width: 0, align: 'center'},
            {name: 'bNameCn', index: 'bNameCn', width: 0, align: 'center'},
            {name: 'modifyId', index: 'modifyId', width: 0, align: 'center', hidden: true},
            {name: 'groupId', index: 'groupId', width: 0, align: 'center', hidden: true},
            {name: 'delStatus', index: 'delStatus', width: 0, align: 'center',hidden: true},
            {name: 'birthday', index: 'birthday', width: 0, align: 'center'},
            {name: 'modifyTime', index: 'modifyTime', width: 0, align: 'center',hidden: true},
            {name: 'createTime', index: 'createTime', width: 0, align: 'center', hidden: true}
        ]
    };
    var accountRelProjectGridSetting = {
        gridId: projectGridTableSelector,
        pagerId: '#project-pager',
        datatype: 'local',
        data: [],
        //height: 130,
        gridHeightType: 2,
        url: null,
        multiselect: true,
        rownumbers: true,
        altRows: true,
        autowidth: true,
        rowNum: 5,
        rowList: [5, 15, 30, 100],
        colNames: ['id', '项目名称', '项目权限'],
        colModel: [
            {name: 'id', index: 'id', width: 0, align: 'center', hidden: true},
            {name: 'name', index: 'name', width: 0, align: 'center'},
            {name: 'projectAuto', index: 'projectAuto', width: 0, align: 'center'}
        ]
    };
    var accountRelDbConnInfoGridSetting = {
        gridId: dbInfoTableSelector,
        pagerId: '#dbInfo-pager',
        datatype: 'local',
        data: [],
        gridHeightType: 2,
        //height: 130,
        url: null,
        multiselect: true,
        rownumbers: true,
        autowidth: true,
        rowNum: 5,
        rowList: [5, 15, 30, 100],
        colNames: ['id', '连接信息名称'],
        colModel: [
            {name: 'id', index: 'id', width: 0, align: 'center', hidden: true},
            {name: 'name', index: 'name', width: 0, align: 'center'}
        ]
    };
    var addProjectGridSetting = {
        gridId: addProjectJqgridTableSelector,
        pagerId: '#addProjectJqPagerTable',
        datatype: 'local',
        data: [],
        //height: 500,
        gridHeightType: 2,
        url: null,
        multiselect: true,
        rownumbers: true,
        altRows: true,
        autowidth: true,
        rowNum: 10,
        rowList: [10, 30, 50],
        colNames: ['id', '项目名称'],
        colModel: [
            {name: 'id', index: 'id', width: 0, align: 'center', hidden: true},
            {name: 'name', index: 'name', width: 0, align: 'center'}
        ]
    };
    var addDbGridSetting = {
        gridId: addDbJqgridTableSelector,
        pagerId: '#addDbJqgridPager',
        datatype: 'local',
        data: [],
        //height: 550,
        gridHeightType: 2,
        url: null,
        multiselect: true,
        rownumbers: true,
        autowidth: true,
        rowNum: 10,
        rowList: [10, 30, 50],
        colNames: ['id', '连接信息名称'],
        colModel: [
            {name: 'id', index: 'id', width: 0, align: 'center', hidden: true},
            {name: 'name', index: 'name', width: 0, align: 'center'}
        ]
    };

    return {
        /**
         初始化
         1.下拉框加载枚举数据
         2.初始化所有表格
         3.查询所有账户信息，并填充到账户信息表格中
         4.绑定按钮
         */
        init: function () {

            function initEnum() {
                sUtils.select2Enum({
                    selector: '#sex',
                    enums: enumMap.get('sec_account-sex'),
                    addAll: true
                });
                sUtils.select2Enum({
                    selector: '#delStatus',
                    enums: enumMap.get('sec_account-delStatus'),
                    addAll: true
                });
                sUtils.select2Enum({
                    selector: '#active',
                    enums: enumMap.get('sec_account-active'),
                    addAll: true
                });
                sUtils.select2Enum({
                    selector: '#status',
                    enums: enumMap.get('sec_account-status'),
                    addAll: true
                });
                sUtils.select2Enum({
                    selector: '#projectAuto',
                    enums: enumMap1.get('pdm_account_rel_project-projectAuto'),
                    addAll: true
                });
                sUtils.select2Enum({
                    selector: '#projectAutoValue',
                    enums: enumMap1.get('pdm_account_rel_project-projectAuto'),
                });
            }

            function initJqGrid(setting){
                sGrid.jqgridSimple(setting);
                sGrid.jqgridTabReSize(setting);
                sGrid.jqgridNotButton(setting['gridId'], setting['pagerId']);
                sGrid.jqgridDestory(setting['gridId']);
            }

            initEnum();
            accountManager.searchAccountInfo(true);
            accountManager.searchAccountInfo(false);

            initJqGrid(accountRelProjectGridSetting);
            initJqGrid(accountRelDbConnInfoGridSetting);
            initJqGrid(addProjectGridSetting);
            initJqGrid(addDbGridSetting);

            $('#clearAccountSearchFormBtn').click(function () {
                accountManager.clearSearchFrom(searchAccountForm);
                accountManager.searchAccountInfo(false);
            });

            $('#clearProjectSearchFormBtn').click(function () {
                accountManager.clearSearchFrom(searchProjectForm);
                accountManager.searchProjectOrDb(true);
            });

            $('#clearDbConnInfoSearchFormBtn').click(function () {
                accountManager.clearSearchFrom(searchDbConnInfoForm);
                accountManager.searchProjectOrDb(false);
            });

        },

        /**
         * 查询账户信息
         * @param flag
         *  flag:true 首次加载，初始化表格 flag:false 二次加载，查找数据
         */
        searchAccountInfo: function (flag) {
            if (flag) {
                //第一次加载，初始化表格
                sGrid.jqgridSimple(accountGridSetting);
                sGrid.jqgridReSize(accountGridSetting);
                sGrid.jqgridNotButton(accountGridSetting['gridId'], accountGridSetting['pagerId']);
                sGrid.jqgridDestory(accountGridSetting['gridId']);
                slog.log('find方法获取所有对象');

            }
            else {
                var params = sUtils.getFormParams(searchAccountForm);
                slog.log(params);
                var findUrl = path + '/action/security/account/find';
                slog.log(findUrl);
                sPost.ajaxFind(findUrl, params, function (data) {
                    if (data.success) {
                        slog.log("search 成功！");
                        slog.log(data);
                        var resData = data.obj;
                        sUtils.transactionEnum(resData.rows, enums, enumMap);
                        $(accountGridTableSelector).clearGridData();
                        $(accountGridTableSelector).setGridParam({data: resData.rows});
                        $(accountGridTableSelector).trigger("reloadGrid");
                    } else {
                        slog.error("search 失败 Error : " + data.msg);
                    }
                });
            }
        },

        /**
         * 单击用户表格行查询账户关联数据
         * @param flag
         *  flag:true 查询关联项目 flag:false 查询关联数据库连接
         */
        searchAccountRelations: function(flag) {

            id = $(accountGridTableSelector).jqGrid('getGridParam', 'selrow');

            if (flag) {
                if (sUtils.notNull(id)) {
                    sPost.ajax(getProUrl, {'id': id}, function (data) {
                        if (data.success) {
                            slog.log("查询项目关联账户成功");
                            var resultData = data.obj;
                            sUtils.transactionEnum(resultData, enums1, enumMap1);
                            slog.log(resultData);
                            $(projectGridTableSelector).clearGridData();
                            $(projectGridTableSelector).setGridParam({data: resultData});
                            $(projectGridTableSelector).trigger("reloadGrid");
                        } else {
                            slog.error("get method error: " + data.msg);
                        }
                    });
                }
            }
            else {
                slog.log(id);
                if (sUtils.notNull(id)) {
                    sPost.ajax(getDbUrl, {'id': id}, function (data) {
                        if (data.success) {
                            slog.log("查询数据库关联账户成功");
                            var accountData = data.obj;
                            slog.log(accountData);
                            $(dbInfoTableSelector).clearGridData();
                            $(dbInfoTableSelector).setGridParam({data: accountData});
                            $(dbInfoTableSelector).trigger("reloadGrid");
                        } else {
                            slog.error("get method error: " + data.msg);
                        }
                    });
                }
            }
        },

        /**
         * 查询项目信息或数据库连接信息
         * @param flag
         *  flag:true 查询项目信息 flag:false 查询数据库连接信息
         */
        searchProjectOrDb: function (flag) {

            var params;

            if (flag) {
                params = sUtils.getFormParams(searchProjectForm);
                sPost.ajaxFind(findAllProjectUrl, params, function (data) {
                    if (data.success) {
                        slog.log("查询项目关联账户成功");
                        var accountData = data.obj;
                        slog.log(accountData);
                        $(addProjectJqgridTableSelector).clearGridData();
                        $(addProjectJqgridTableSelector).setGridParam({data: accountData});
                        $(addProjectJqgridTableSelector).trigger("reloadGrid");
                    } else {
                        slog.log("查询项目关联账户失败");
                    }
                });
            } else {
                params = sUtils.getFormParams(searchDbConnInfoForm);
                sPost.ajaxFind(findAllDbUrl, params, function (data) {
                    if (data.success) {
                        slog.log("查询数据库关联账户成功");
                        var accountData = data.obj;
                        slog.log(accountData);
                        $(addDbJqgridTableSelector).clearGridData();
                        $(addDbJqgridTableSelector).setGridParam({data: accountData});
                        $(addDbJqgridTableSelector).trigger("reloadGrid");
                    } else {
                        slog.log("查询数据库关联账户失败");
                    }
                });
            }
        },

        /**
         打开添加关联项目或数据库连接信息弹窗
         1、点击管理项目栏添加按钮打开弹窗
         2、查询所有项目信息
         3、将获取的项目信息填充到到弹出表格中
         4、勾选需要添加的项目
         5、点击确认将项目管理添加到给该用户
         6、再次初始化项目管理表格
         *
         *  @param flag
         *      flag:true 添加关联项目 flag:false 添加关联数据库连接信息
         */
        openWinProjectOrDb: function (flag) {

            var index;

            // 获取选中行id
            id = $(accountGridTableSelector).jqGrid('getGridParam', 'selrow');

            if (sUtils.isNull(id)) {
                layer.alert('请选定用户！', {icon: 5, title: '提示'});
                return;
            }

            if(flag){
                $(addedAccRelProjTableSelector)[0].options.length = 0;
                sPost.ajaxFind(findAllProjectUrl, {}, function (data) {
                    if (data.success) {
                        slog.log("查询项目关联账户成功");
                        var accountData = data.obj;
                        slog.log(accountData);
                        $(addProjectJqgridTableSelector).clearGridData();
                        $(addProjectJqgridTableSelector).setGridParam({data: accountData});
                        $(addProjectJqgridTableSelector).trigger("reloadGrid");
                    } else {
                        slog.log("查询项目关联账户失败");
                    }
                });
                index = layer.open({
                    type: 1,
                    title: '添加关联项目',
                    shadeClose: true,
                    //shade: 0.8,
                    area: ['1100px', '500px'],
                    content: $('#accAddProjectModal'),
                    zIndex: 1000
                });

                $('#saveProjectAccBtn').unbind('click').click(function() {
                    if (-1 == accountManager.saveAccRelProjOrDbConnInfo(true)) {
                        return;
                    }
                    layer.close(index);
                    accountManager.searchAccountRelations(true);
                });

                $('#removeProjectAccBtn').unbind('click').click(function(){
                    layer.close(index);
                });
            }else{
                $(addedAccRelDbTableSelector)[0].options.length = 0;
                sPost.ajaxFind(findAllDbUrl, {}, function (data) {
                    if (data.success) {
                        slog.log("查询连接信息关联账户成功");
                        var accountData = data.obj;
                        slog.log(accountData);
                        $(addDbJqgridTableSelector).clearGridData();
                        $(addDbJqgridTableSelector).setGridParam({data: accountData});
                        $(addDbJqgridTableSelector).trigger("reloadGrid");
                    }

                });

                index = layer.open({
                    type: 1,
                    title: '添加连接信息',
                    shadeClose: true,
                    //shade: 0.8,
                    area: ['1100px', '500px'],
                    content: $('#accAddDbModal'),
                    zIndex: 1000
                });
                $('#saveDbRelAccBtn').unbind('click').click(function() {
                    if (-1 == accountManager.saveAccRelProjOrDbConnInfo(false)) {
                        return;
                    }
                    layer.close(index);
                    accountManager.searchAccountRelations(false);
                });

                $('#removeDbRelAccBtn').unbind('click').click(function(){
                    layer.close(index);
                });
            }
        },

        /**
         * 添加已选项目或数据库连接信息到已选择表格中
         *
         * @param flag
         *      flag:true 添加项目 flag:false 添加数据库连接信息
         */
        addProjectOrDbConnInfoToTable: function (flag) {

            var options;

            function addToTable(gridId, tableId, options) {

                var option;
                var resData;

                var selectedIds = $(gridId).jqGrid("getGridParam", "selarrrow");
                slog.log(selectedIds);
                if (sUtils.isNull(selectedIds)) {
                    layer.alert('请选定用户！', {icon: 5, title: '提示'});
                    return;
                }

                var array = options.map(function () {
                    return $(this).val();
                });
                slog.log(array);

                $.each(selectedIds, function (idx, val) {
                    //判断下拉框有没有重复的id，如果有就不加进去
                    if ($.inArray(val, array) == -1) {
                        resData = $(gridId).jqGrid('getRowData', val);
                        option = $("<option>").val(val).text(resData.name);
                        $(tableId).append(option);
                    }
                });
            }

            if (flag) {
                slog.log("用户关联项目添加");

                options = $('#addedAccRelProjTable option');
                addToTable(addProjectJqgridTableSelector, addedAccRelProjTableSelector, options);
            } else {
                slog.log("连接信息添加");

                options = $('#addedAccRelDbTable option');
                addToTable(addDbJqgridTableSelector, addedAccRelDbTableSelector, options);
            }
        },

        /**
         * 移除已添加的项目或数据库
         *
         * @param flag
         *      flag:true 添加项目 flag:false 添加数据库连接信息
         */
        removeProjectOrDb: function (flag) {
            var $option = flag ? $(addedAccRelProjTableSelector) : $(addedAccRelDbTableSelector);
            $option = $option.find("option:selected");
            if ($option.length == 0) {
                layer.alert('请选择要移除的选项！', {icon: 5, title: '提示'});
            } else {
                $option.remove();
            }
        },
        /**
         *  添加账户关联 项目或数据库信息关系
         *
         * @param flag
         *  flag:true 添加关联项目 flag:false 添加关联数据库连接信息
         *
         * @returns {number}
         *  -1： 未选择添加选项。
         *
         */
        saveAccRelProjOrDbConnInfo: function (flag) {

            var url;

            if (flag) {
                slog.log("添加项目关联账户关系");

                var projectOptions = $('#addedAccRelProjTable option');

                if (projectOptions.length == 0) {
                    layer.alert('请添加项目！', {icon: 5, title: '提示'});
                    return -1;
                }

                var projectIds = projectOptions.map(function () {
                    return $(this).val();
                }).get().join(",");

                slog.log(projectIds);

                var selectParams = $('#projectAutoValue option:selected').attr('value');

                url = action + 'accountManage/saveAccountRelProject';
                sPost.ajax(url, {'id': parseFloat(id), 'ids': projectIds, 'right': selectParams}, function (data) {
                    if (data.success) {
                        slog.log("添加项目关联账户关系成功！");
                        slog.log(data);
                        layer.alert('添加账户关联项目关系成功！', {icon: 1, title: '提示'});
                    } else {
                        slog.error("add Method Error : " + data.msg);
                    }
                });
            } else {
                slog.log("添加连接信息关联账户关系");
                var dbConnInfoOptions = $('#addedAccRelDbTable option');

                if (dbConnInfoOptions.length == 0) {
                    layer.alert('请添加连接信息！', {icon: 5, title: '提示'});
                    return -1;
                }

                var DbConnInfoIds = dbConnInfoOptions.map(function () {
                    return $(this).val();
                }).get().join(",");

                slog.log(DbConnInfoIds);

                url = action + 'accountManage/saveAccountRelDbConnInfo';
                sPost.ajax(url, {'id': parseFloat(id), 'ids': DbConnInfoIds}, function (data) {
                    if (data.success) {
                        slog.log("添加连接信息关联账户关系成功！");
                        slog.log(data);
                        layer.alert('添加账户关联连接信息关系成功！', {icon: 1, title: '提示'});
                    } else {
                        slog.error("add Method Error : " + data.msg);
                    }
                });
            }
        },

        /**
         * 删除账户关联 项目或数据库信息关系
         *
         * @param flag
         *  flag:true 删除关联项目 flag:false 删除关联数据库连接信息
         */
        delProjectOrDb: function (flag) {

            // 获取选中账户表行id
            id = $(accountGridTableSelector).jqGrid('getGridParam', 'selrow');
            var selectedIds;

            if (flag) {
                // 获取选中关联表行id
                selectedIds = $(projectGridTableSelector).jqGrid("getGridParam", "selarrrow");

                if (sUtils.isNull(selectedIds)) {
                    layer.alert('请选定用户！', {icon: 5, title: '提示'});
                    return;
                }

                var delProjectIds = selectedIds.join(",");

                slog.log(delProjectIds);

                layer.confirm('确定要删除吗？', {icon: 3, title: '提示'}, function (index) {

                    var delProjectUrl = action + 'accountManage/deleteAccountRleProject';
                    sPost.ajax(delProjectUrl, {'id': parseFloat(id), 'ids': delProjectIds}, function (data) {
                        if (data.success) {
                            slog.log("Delete Method 成功！");
                            slog.log(data);

                            while (selectedIds.length) {
                                $(projectGridTableSelector).jqGrid("delRowData", selectedIds[0]);
                            }
                            layer.alert('删除成功！', {icon: 1, title: '提示'});
                        } else {
                            slog.error("Delete Method Error : " + data.msg);
                            layer.alert('删除失败！', {icon: 5, title: '提示'});
                        }
                    });
                    layer.close(index);
                });
            } else {
                // 获取选中行id
                selectedIds = $(dbInfoTableSelector).jqGrid("getGridParam", "selarrrow");

                if (sUtils.isNull(selectedIds)) {
                    layer.alert('请选定用户！', {icon: 5, title: '提示'});
                    return;
                }

                var delDbIds = selectedIds.join(',');
                slog.log(delDbIds);

                layer.confirm('确定要删除吗？', {icon: 3, title: '提示'}, function (index) {

                    sPost.ajax(delDbUrl, {'id': parseFloat(id), 'ids': delDbIds}, function (data) {
                        if (data.success) {
                            slog.log("Delete Method 成功！");
                            slog.log(data);

                            while (selectedIds.length) {
                                $(dbInfoTableSelector).jqGrid("delRowData", selectedIds[0]);
                            }
                            layer.alert('删除成功！', {icon: 1, title: '提示'});
                        } else {
                            slog.error("Delete Method Error : " + data.msg);
                            layer.alert('删除失败！', {icon: 5, title: '提示'});
                        }
                    });
                    layer.close(index);
                });
            }
        },

        /**
         * 清空查询条件
         *
         * @param formId
         *  表单id，如有特殊控件，可单独处理
         */
        clearSearchFrom: function (formId) {
            sUtils.cleanFrom(formId);
            if (formId == searchAccountForm) {
                $('#accountDelStatus').val(0);
                $('#sex').select2('val', '');
            }
        }
    }
}();